package com.spring.library.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.spring.library.common.Result;
import com.spring.library.entity.User;
import com.spring.library.service.IUserService;
import com.spring.library.utils.JwtUtil;
import com.spring.library.utils.Md5Util;
import com.spring.library.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author danty
 * @since 2024-09-19
 */
@RestController
@CrossOrigin
@RequestMapping("/library/user")
@Validated
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/register")
    public Result register(@RequestBody User user){
        //校验非空
        String userName = user.getUserName();
        if (userName == null || userName.isEmpty()) {
            return Result.error("用户名为空");
        }
        if (user.getUserEmail() == null || user.getUserEmail().isEmpty()) {
            return Result.error("邮箱为空");
        }
        if (user.getUserPassword() == null || user.getUserPassword().isEmpty()) {
            return Result.error("密码为空");
        }
        //校验用户名是否存在:
        //1.Mapper接口
        /*if(userService.findByName(user.getUserName())!=null){
            return Result.error("用户名已存在");
        }*/
        //2.在service中用QueryWrapper进行条件查询
        Result register = userService.register(user);
        return Result.success(register);
    }



    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        User loginUser = userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, user.getUserName())
                .eq(User::getUserPassword, Md5Util.getMD5String(user.getUserPassword())));
        if (loginUser != null) {
            // 生成 token
            Map<String, Object> claims = new HashMap<>();
            String key = user.getUserName() + UUID.randomUUID();
            claims.put("token", key);
            String token = JwtUtil.genToken(claims);
            // 将 Token 存入 Redis 缓存中
            redisTemplate.opsForValue().set(token, loginUser, 30, TimeUnit.MINUTES);
            // 将 token 存入 ThreadLocal
            ThreadLocalUtil.set(token);
            System.out.println("Token set: " + ThreadLocalUtil.get());
            return Result.success(token);
        } else {
            return Result.error("用户名或密码错误！");
        }
    }


    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable("id") Integer id){
        if(!userService.removeById(id)){
            return Result.error("用户id为空，无法删除");
        }return Result.success("删除成功");
    }

    //管理员修改用户状态
    @PutMapping("/updateStatus")
    public Result updataUserStatus(@RequestBody User user) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", user.getUserId()) // 使用目标用户 ID
                .set("user_status",user.getUserStatus());
        boolean result = userService.update(updateWrapper); // 调用 update 方法
        if (result) {
            return Result.success("状态重置");
        } else {
            return Result.error("修改失败，可能是其他问题!");
        }
    }



    /**
     * 通过token校验当前用户信息
     * @return
     */
    @GetMapping("/getUserInfo")
    public Result getUserInfo() {
        String token = ThreadLocalUtil.get();
        User user = (User) redisTemplate.opsForValue().get(token);
        System.out.println("user = " + user);
        return Result.success(user);
    }
    /**
     * 获取所有用户信息
     * @return
     */
    @GetMapping({"/getAll"})
    public Result<List<User>> getAllUser() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_role", "USER");
        List<User> users = userService.list(queryWrapper);
        return Result.success(users);
    }

    /**
     * 检查用户是否为管理员
     * @param user
     * @return
     */
    @PostMapping("/isAdmin")
    public Result checkAdmin(@RequestBody User user){
        String userName = user.getUserName();
        String userRole = userService.findByName(userName).getUserRole();
        return Result.success(userRole);
    }

    /**
     * 用户注销操作
     * @param token
     * @return
     */
    @PostMapping("/logout")
    public Result logOut(@RequestHeader String token){
        Boolean delete = redisTemplate.delete(token);
        if (delete) {
            return Result.success("注销成功");
        }
        return Result.success("注销失败");
    }



}
